package com.junyuan.bluetooth;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button connection, disconnection, sendMessage, sendDelay;
    private BleUtils bleUtils;
    private MyBroadcastReceiver myBroadcastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bleUtils = new BleUtils();
        bleUtils.initBle(this);

        connection = (Button) findViewById(R.id.btnConnect);
        disconnection = (Button) findViewById(R.id.btnDisConnect);
        sendMessage = (Button) findViewById(R.id.btnSend);
        sendDelay = (Button) findViewById(R.id.btnSendDelay);

        connection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent linkbleIntent = new Intent();
                linkbleIntent.setAction("linkble");
                sendBroadcast(linkbleIntent);
            }
        });

        disconnection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bleUtils.disconnect();
            }
        });

        sendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bleUtils.sendData("haha", 0);
            }
        });

        sendDelay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bleUtils.sendData("delay", 1000);
            }
        });

        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter filter = new IntentFilter("BackData");
        registerReceiver(myBroadcastReceiver, filter);


    }

    class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String backData = intent.getStringExtra("BackData");
            Log.d("123", "MoreMusicActivity的广播接收到：" + backData);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bleUtils.closeBle();
        unregisterReceiver(myBroadcastReceiver);
    }
}
